package com.zd.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.zd.entity.User;
import com.zd.service.UserService;
import com.zd.service.impl.UserServiceImpl;

/**
 * Servlet implementation class userLoginServlet
 */
@WebServlet("/UserLoginServlet")
public class UserLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String userId=request.getParameter("userId");
		String userPass=request.getParameter("userPass");
		response.setContentType("application/JSON");
		
		System.out.println(userId+userPass+111);
		UserService userLoginService=new UserServiceImpl();
		User user=userLoginService.login(userId,userPass);
		HttpSession session=request.getSession();
//		request.setAttribute("user", user);
		session.setAttribute("user", user);
		System.err.println(session.getAttribute("user")+"uuuuuu");
		if(user==null) {
			request.getSession().setAttribute("mes","账号或密码有误，请检查");
			
			System.out.println("登录失败");
			response.sendRedirect("login.jsp");
			return;
		}
		if(user.getAdmin()==1) {
			response.sendRedirect("admin.jsp");
			return;
		}
		request.getSession().setAttribute("mes","");
		response.sendRedirect("index.jsp");
//		Map<String,List<User>> map=new HashMap<String,List<User>>();
//		List<User> listUser=new ArrayList<User>();
//		listUser.add(user);
//		map.put("listUser", listUser);
////		if(user==null) {
////			System.out.println("登陆失败");
////		}
////		request.getRequestDispatcher("index.jsp").forward(request, response);
//		
//		
//		String jsonString=JSON.toJSONString(map);
//		
//		PrintWriter out=response.getWriter();
//		out.print(jsonString);
//		out.flush();
//		out.close();
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
